import 'dart:convert';

import 'package:changxindianzishangwu/cache/local_cache.dart';
import 'package:changxindianzishangwu/dao/sms_code_dao.dart';
import 'package:changxindianzishangwu/db/ec_cache.dart';
import 'package:changxindianzishangwu/http/base/ec_base_request.dart';
import 'package:changxindianzishangwu/http/request/login_account_pwd.dart';
import 'package:changxindianzishangwu/http/request/login_account_register.dart';
import 'package:changxindianzishangwu/http/request/login_apple_request.dart';
import 'package:changxindianzishangwu/http/request/login_auth_request.dart';
import 'package:changxindianzishangwu/http/request/login_binding_phone_request.dart';
import 'package:changxindianzishangwu/http/request/login_check_qr_user_request.dart';
import 'package:changxindianzishangwu/http/request/login_mobile_request.dart';
import 'package:changxindianzishangwu/http/request/login_verify_request.dart';
import 'package:changxindianzishangwu/http/request/password_login_request.dart';
import 'package:changxindianzishangwu/http/request/qr_code_login_request.dart';
import 'package:changxindianzishangwu/http/request/regis_sms_request.dart';
import 'package:changxindianzishangwu/http/zd_net.dart';
import 'package:changxindianzishangwu/model/base_model.dart';
import 'package:changxindianzishangwu/model/user_info_model.dart';
import 'package:changxindianzishangwu/model/we_chat_user_info_model.dart';
import 'package:changxindianzishangwu/util/toast.dart';
import 'package:crypto/crypto.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:tencent_im_sdk_plugin/tencent_im_sdk_plugin.dart';
import 'package:tpns_flutter_plugin/tpns_flutter_plugin.dart';

class LoginType {
  static const int LOGIN_QQ = 1;
  static const int LOGIN_WX = 2;
  static const int LOGIN_APPLE = 3;
}

String generateMd5(String input) {
  return md5.convert(utf8.encode(input)).toString();
}

class LoginInitDao {
  static loginVerify(String telephone, String areaCode) {
    return _send(telephone: telephone, areaCode: areaCode);
  }

  static login(String telephone, String password) {
    return _send(telephone: telephone, password: password);
  }

  static regis(String telephone, String areaCode, String verificationCode) {
    return _send(
        telephone: telephone,
        areaCode: areaCode,
        verificationCode: verificationCode);
  }

  static loginForMobileToken(String mobileToken) {
    print('获取到的token${mobileToken}');
    return _send(mobileToken: mobileToken);
  }

  static logout(String accessToken, String phoneToken) {
    return _send(accessToken: accessToken, phoneToken: phoneToken);
  }

  static _send(
      {String telephone,
      String password,
      String areaCode,
      String verificationCode,
      String mobileToken,
      String accessToken,
      String phoneToken,
      String language = "cn"}) async {
    EcBaseRequest request;
    if (password == null &&
        areaCode != null &&
        verificationCode == null &&
        telephone != null) {
      request = LoginVerifyRequest();
    } else if (areaCode != null &&
        verificationCode != null &&
        language != null) {
      print(1);

      request = RegisSmsRequest();
    } else if (password != null) {
      telephone = generateMd5(telephone);
      password = generateMd5(password);
      //账号密码登录
      request = PasswordLoginRequest();
    } else if (mobileToken != null) {
      //一键登录
      request = LoginMobileTokenRequest();
    } else if (accessToken != null && telephone != null) {
      //登出
      request = logout(accessToken, telephone);
    }

    print('---areaCode----${areaCode}');
    request
        .add("telephone", telephone ?? "")
        .add("password", password ?? "")
        .add("areaCode", areaCode ?? "")
        .add("verificationCode", verificationCode ?? "")
        .add("mobileToken", mobileToken ?? "")
        .add("access_token", accessToken ?? "")
        .add("language", language);
    EasyLoading.show(status: "登录中.....");

    Map result = await ZdNet.getInstance().send(request);
    print('登录返回数据:  ${json.encode(result)}');
    EasyLoading.dismiss();

    if (result["resultCode"] != 0 && result["resultMsg"] == "手机号未注册") {
      SmsCodeDao.getCode(telephone, areaCode, REGIS);
      return Get.toNamed("/getMessagePage", arguments: {
        "telephone": telephone,
        "areaCode": areaCode,
        "flag": false
      });
    }

    if (result["resultCode"] == 0 && result["resultMsg"] == "手机号已注册") {
      return Get.toNamed("/passwordLoginPage", arguments: {
        "telephone": telephone,
        "areaCode": areaCode,
      });
    } else if (result["resultCode"] == 0) {
      return showToast(
          result.containsKey("resultMsg") ? result["resultMsg"] : "登录失败");
    } else if (result["data"] != null && result['resultCode'] != 0) {
      print("登陆成功-----------$result");
      setUserinfo(result);
      print("getAppLoginToken=========" + getAppLoginToken());
      print("userid=========" + getUserId());
      print("userSig==========" + getUserSig());
      Get.offAllNamed(
        "/homePage",
        arguments: getAppLoginToken(),
      );
      TencentImSDKPlugin.v2TIMManager
          .login(
        userID: getUserId(),
        userSig: getUserSig(),
      )
          .then((res) async {
        if (res.code == 0) {
          final XgFlutterPlugin tpush = new XgFlutterPlugin();
          tpush.setAccount(getUserId(), AccountType.UNKNOWN);
          showToast("登录成功");
          return Get.offAllNamed(
            "/homePage",
            arguments: getAppLoginToken(),
          );
        } else
          print("IM登录失败${json.encode(res)}");
        ;
      });
    }

    // else if (result["resultMsg"] == "短信验证码不正确!" ||
    //     result["resultCode"] == 0 ||
    //     result['resultMsg'] == "验证码已无效，请重新获取验证码") {
    //   EasyLoading.dismiss();
    //   if (result["resultMsg"] == "短信验证码不正确!") {
    //     return showToast("验证码不正确！");
    //   } else if (result['resultMsg'] == "验证码已无效，请重新获取验证码") {
    //     return showToast("验证码已无效，请重新获取验证码!");
    //   }
    //   return showToast("请返回重试！");
    // }
  }

  static loginAuth(String token) async {
    EcBaseRequest request = LoginAuthRequest();
    request.add("mobileToken", token);
    print('------mobileToken:$token');
    var result = await ZdNet.getInstance().send(request);
    UserInfoModel userInfoModel = UserInfoModel.fromJson(result);
    if (userInfoModel.resultCode == 1) setUserinfo(result);
    return userInfoModel;
  }

  static accountRegister(String account, String pwd) async {
    EcBaseRequest request = LoginAccountPwd();
    request
        .add("loginType", 0)
        .add("account", account)
        .add("password", generateMd5(pwd));
    var result = await ZdNet.getInstance().send(request);
    UserInfoModel userInfoModel = UserInfoModel.fromJson(result);
    if (userInfoModel.resultCode == 1) setUserinfo(result);
    return userInfoModel;
  }
  static loginAccount(String account, String pwd) async {
    EcBaseRequest request = LoginAccountRequest();
    request
        .add("loginType", 0)
        .add("account", account)
        .add("password", generateMd5(pwd));
    var result = await ZdNet.getInstance().send(request);
    UserInfoModel userInfoModel = UserInfoModel.fromJson(result);
    if (userInfoModel.resultCode == 1) setUserinfo(result);
    return userInfoModel;
  }
  static msmRegister(
      String telephone, String areaCode, String verificationCode) async {
    EcBaseRequest request = RegisSmsRequest();
    request
        .add("telephone", telephone)
        .add("areaCode", areaCode)
        .add("verificationCode", verificationCode);
    var result = await ZdNet.getInstance().send(request);
    int code = result["resultCode"];
    if (code != 1) return code;
    UserInfoModel userInfoModel = UserInfoModel.fromJson(result);
    if (userInfoModel.resultCode == 1) setUserinfo(result);
    return userInfoModel;
  }

  ///扫码登录
  static qrLogin(String qrCodeKey, int type) async {
    EcBaseRequest request = QrCodeLoginRequest();
    request
        .add("qrCodeKey", qrCodeKey)
        .add("access_token", getAppLoginToken())
        .add("type", type);
    var result = await ZdNet.getInstance().send(request);
    return BaseModel.fromJson(result);
  }

  ///第三方授权=》检查openID是否有绑定用户
  ///第三方登录类型 0普通注册 1：QQ 2:微信 3:apple
  static checkQrUser(type, {String loginInfo, String mobileToken}) async {
    EcBaseRequest request = LoginCheckQrUserRequest();
    request
        .add("type", type)
        .add("loginInfo", loginInfo)
        .add("mobileToken", mobileToken);
    var result = await ZdNet.getInstance().send(request);
    int code = result["resultCode"];
    if (code != 1) return BaseModel.fromJson(result);
    UserInfoModel userInfoModel = UserInfoModel.fromJson(result);
    if (userInfoModel.resultCode == 1) setUserinfo(result);
    return userInfoModel;
  }

  /// Account=手机号 账号，pwd=验证码 密码
  ///type0普通注册 1：QQ 2:微信 3:apple
  ///bindingType 1绑定手机号 2绑定账号密码
  static loginBindingPhone(WeChatUserInfoModel _wxInfo, account, pwd,
      {String areaCode, int bindingType = 1}) async {
    EcBaseRequest request = LoginBindingPhoneRequest();
    request.add("type", _wxInfo.loginType).add("loginInfo", _wxInfo.openid);
    // .add("account", account)
    // .add("nickname", _wxInfo.nickname)
    // .add("avatar", _wxInfo.headimgurl)
    // .add("sex", _wxInfo.sex)
    if (bindingType == 1) {
      request
          .add("telephone", account)
          .add("areaCode", areaCode)
          .add("verificationCode", pwd);
    } else {
      request.add("account", account).add("password", generateMd5(pwd));
    }

    var result = await ZdNet.getInstance().send(request);
    int code = result["resultCode"];
    if (code != 1) return BaseModel.fromJson(result);
    if (code == 1) {
      UserInfoModel userInfoModel = UserInfoModel.fromJson(result);
      setUserinfo(result);
      return userInfoModel;
    }
  }

// static loginApple(identityToken) async {
//   EcBaseRequest request = LoginAppleRequest();
//   request
//       .add("loginInfo", "")
//       .add("type", 3)
//       .add("mobileToken", identityToken);
//   var result = await ZdNet.getInstance().send(request);
//   int code = result["resultCode"];
//   if (code != 1) return code;
//   UserInfoModel userInfoModel = UserInfoModel.fromJson(result);
//   if (userInfoModel.resultCode == 1) setUserinfo(result);
//   return userInfoModel;
// }
}
